package com.pet.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.pet.behavior.mapper.ApLikesBehaviorMapper;
import com.pet.behavior.service.ApBehaviorEntryService;
import com.pet.behavior.service.ApLikesBehaviorService;
import com.pet.common.constants.MQConstants;
import com.pet.common.exception.LeadNewsException;
import com.pet.model.behavior.dtos.LikesBehaviorDto;
import com.pet.model.behavior.dtos.UpdateArticleMsg;
import com.pet.model.behavior.pojos.ApBehaviorEntry;
import com.pet.model.behavior.pojos.ApLikesBehavior;
import com.pet.model.common.dtos.ResponseResult;
import com.pet.model.common.enums.AppHttpCodeEnum;
import com.pet.model.user.pojos.ApUser;
import com.pet.utils.common.JsonUtils;
import com.pet.utils.threadlocal.ThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

/**
 * <p>
 * APP点赞行为表 服务实现类
 * </p>
 */
@Service
@Transactional
public class ApLikesBehaviorServiceImpl extends ServiceImpl<ApLikesBehaviorMapper, ApLikesBehavior> implements ApLikesBehaviorService {

    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;

    @Autowired
    private KafkaTemplate          kafkaTemplate;

    @Override
    public ResponseResult likes(LikesBehaviorDto dto) {
        //1.取出登录用户信息
        ApUser user = (ApUser) ThreadLocalUtils.get();
        Integer userId = null;
        if (user != null) {
            userId = user.getId();
        }
        //2.取出登录设备信息
        Integer equipmentId = dto.getEquipmentId();
        //3.根据用户/设备信息获取行为实体信息
        ApBehaviorEntry behaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(userId, equipmentId);

        if (behaviorEntry == null) {
            throw new LeadNewsException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        try {
            //4.查询是否存在点赞行为记录
            QueryWrapper<ApLikesBehavior> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("entry_id", behaviorEntry.getId());
            queryWrapper.eq("article_id", dto.getArticleId());
            ApLikesBehavior likesBehavior = getOne(queryWrapper);
            if (likesBehavior == null && dto.getOperation().equals(0)) {
                //5.如果没有记录，且operation为0，添加点赞行为记录
                likesBehavior = new ApLikesBehavior();
                likesBehavior.setArticleId(dto.getArticleId());
                likesBehavior.setEntryId(behaviorEntry.getId());
                likesBehavior.setCreatedTime(new Date());
                likesBehavior.setType(dto.getType());
                likesBehavior.setOperation(dto.getOperation());
                save(likesBehavior);
                //用户点赞先查询用户标签是否绑定，如果绑定，则不添加数据
            } else {
                //6.如果有记录，修改点赞行为记录的operation改为1
                likesBehavior.setOperation(dto.getOperation());
                likesBehavior.setType(dto.getType());
                likesBehavior.setCreatedTime(new Date());
                updateById(likesBehavior);
                //用户取消点赞先查询用户标签是否绑定，如果绑定，则删除数据
            }

            //点赞行为时发送MQ消息
            if (dto.getOperation().equals(0)) {
                UpdateArticleMsg updateArticleMsg = new UpdateArticleMsg();
                updateArticleMsg.setType(UpdateArticleMsg.UpdateArticleType.LIKES);
                updateArticleMsg.setArticleId(dto.getArticleId());

                kafkaTemplate.send(MQConstants.HOT_ARTICLE_INPUT_TOPIC, UUID.randomUUID().toString(), JsonUtils.toString(updateArticleMsg));
            }
            //文章发生点赞行为时发送MQ消息
            HashMap<String, Object> map = Maps.newHashMap();
            map.put("articleId", dto.getArticleId());
            map.put("operation", dto.getOperation());
            map.put("userId", userId);
            kafkaTemplate.send(MQConstants.ARTICLE_LABEL_USER_TOPIC, UUID.randomUUID().toString(), JsonUtils.toString(map));

            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            throw new LeadNewsException(AppHttpCodeEnum.SERVER_ERROR);
        }

    }

    @Override
    public ResponseResult<ApLikesBehavior> getLikeBehavior(Integer entryId, Long articleId) {
        QueryWrapper<ApLikesBehavior> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("entry_id", entryId);
        queryWrapper.eq("article_id", articleId);
        return ResponseResult.okResult(getOne(queryWrapper));
    }
}
